package com.infore.airsupervise.adapter;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.formatter.DefaultAxisValueFormatter;
import com.github.mikephil.charting.formatter.DefaultValueFormatter;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.infore.airsupervise.R;
import com.infore.airsupervise.bean.PointAnalyzeE;
import com.infore.airsupervise.bean.PointQueryE;
import com.infore.airsupervise.ui.widget.MyMarkerView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.finalteam.toolsfinal.adapter.RecyclingPagerAdapter;

/**
 * 点位分析查询列表适配器
 * <p>
 * 作者: dingxinlin
 * 创建日期: 2017/4/11 9:16
 */

public class PointQueryRecyclerAdapter extends RecyclerView.Adapter<PointQueryRecyclerAdapter.ViewHolder> {

    private List<PointQueryE> sourceData;
    private int dataType;
    private List<List<List<BarEntry>>> mData;
    private List<String> factorNames;
    private List<Integer> colors;
    private List<String> xFormats = new ArrayList<>();
    
    public PointQueryRecyclerAdapter(List<PointQueryE> data, int dataType) {
        this.sourceData = data;
        this.dataType = dataType;

        // 数据转换
        dataTransform(data);

        // 添加颜色
        colors = new ArrayList<>();
        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_chart_recycler, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.chartName.setText(factorNames.get(position));

        // 初始化Chart
        initChart(holder.barChart);

        // 设置BarChart
        setChartData(holder.barChart, position);
    }

    @Override
    public int getItemCount() {
        return mData == null ? 0 : mData.size();
    }

    /**
     * 初始化Chart
     * @param mChart
     */
    private void initChart(BarChart mChart) {
        mChart.setDrawBarShadow(false);
        mChart.setDrawValueAboveBar(true);
        mChart.getDescription().setEnabled(false);

        // scaling can now only be done on x- and y-axis separately
        mChart.setPinchZoom(false);
        mChart.setDrawBarShadow(false);
        mChart.setDrawGridBackground(false);

        // create a custom MarkerView (extend MarkerView) and specify the layout to use for it
        MyMarkerView mv = new MyMarkerView(mChart.getContext(), R.layout.custom_marker_view);
        mv.setChartView(mChart); // For bounds control
        mChart.setMarker(mv); // Set the marker to the chart

        Legend l = mChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setDrawInside(true);
        l.setTextSize(7f);
        l.setFormLineWidth(2f);

        XAxis xAxis = mChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularity(1f);
        xAxis.setCenterAxisLabels(true);
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                int index = (int) value;
                if (index < 0 || index >= xFormats.size()) {
                   return "";
                }
                return xFormats.get(index);
            }
        });

        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.setValueFormatter(new DefaultAxisValueFormatter(2));
        leftAxis.setDrawGridLines(false);
        leftAxis.setSpaceTop(35f);
        //leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
        leftAxis.setGranularityEnabled(true);

        // 隐藏右边Y轴
        mChart.getAxisRight().setEnabled(false);
    }

    /**
     * 设置Chart数据
     * @param mChart
     * @param position
     */
    private void setChartData(BarChart mChart, int position) {
        List<List<BarEntry>> yVals = mData.get(position);

        int gCount = yVals.size();
        int xCount = yVals.get(0).size();

        float groupSpace = 0.08f;
        float barSpace = 0.12f / gCount;
        float barWidth = 0.8f / gCount;

        IBarDataSet[] sets = new IBarDataSet[gCount];

        // 创建DataSet
        for (int i = 0; i < gCount; i++) {
            PointQueryE sta = sourceData.get(i);
            BarDataSet set = new BarDataSet(yVals.get(i), sta.getName());
            set.setColor(colors.get(i));
            sets[i] = set;
        }

        BarData data = new BarData(sets);
        data.setValueFormatter(new DefaultValueFormatter(2));

        mChart.setData(data);

        // specify the width each bar should have
        mChart.getBarData().setBarWidth(barWidth);

        // restrict the x-axis range
        mChart.getXAxis().setAxisMinimum(0);

        // barData.getGroupWith(...) is a helper that calculates the width each group needs based on the provided parameters
        mChart.getXAxis().setAxisMaximum(0 + mChart.getBarData().getGroupWidth(groupSpace, barSpace) * xCount);
        mChart.groupBars(0, groupSpace, barSpace);
        mChart.invalidate();
    }

    /**
     * 数据转换
     * @return
     */
    private void dataTransform(List<PointQueryE> datas) {

        if (datas == null || datas.isEmpty()) {
            return;
        }

        // 结果集
        mData = new ArrayList<>();
        factorNames = new ArrayList<>();
        
        // 参照集
        List<PointQueryE.VlistBean> factorList = datas.get(0).getVlist();
        
        for (int i = 0; i < factorList.size(); i++) {
            PointQueryE.VlistBean factor = factorList.get(i);
            factorNames.add(factor.getFactorName());
            
            // 获取单个因子
            mData.add(getFactorList(datas, i));
        }
    }

    /**
     * 获取单个因子的实体
     * @param datas
     * @param fIndex
     * @return
     */
    private List<List<BarEntry>> getFactorList(List<PointQueryE> datas, int fIndex) {
        // 结果集
        List<List<BarEntry>> yVals = new ArrayList<>();

        // 1.站点
        for (int i = 0; i < datas.size(); i++) {
            List<BarEntry> yVal = new ArrayList<>();

            PointQueryE sta = datas.get(i);
            List<PointQueryE.VlistBean> factorList = sta.getVlist();
            if (factorList == null) {
                break;
            }

            // 2.因子
            PointQueryE.VlistBean factor = factorList.get(fIndex);
            List<PointQueryE.VlistBean.FactorListBean> dataList = factor.getFactorList();
            if (dataList == null) {
                break;
            }

            // 3.数据
            for (int k=0; k<dataList.size(); k++) {
                PointQueryE.VlistBean.FactorListBean data = dataList.get(k);
                String desc = sta.getName() + "\n" + factor.getFactorName() + "：" + data.getValue();
                yVal.add(new BarEntry(k, (float)data.getValue(), desc));

                if (xFormats.size() < dataList.size()) {
                    String time = data.getTime();
                    String xf = dataType == 3 ? time : time.substring(5);
                    xFormats.add(xf);
                }
            }

            yVals.add(yVal);
        }

        return yVals;
    }

    /**
     * ViewHolder
     */
    public class ViewHolder extends RecyclerView.ViewHolder {
        
        public TextView chartName;
        public BarChart barChart;

        public ViewHolder(View itemView) {
            super(itemView);
            chartName = (TextView) itemView.findViewById(R.id.item_chart_name);
            barChart = (BarChart) itemView.findViewById(R.id.item_bar_chart);
        }
    }

}
